package com.peng.leetcode.list;

/**
 * ReverseKGroup1
 * <p>
 * Created on 2022/12/26
 *
 * @author lupeng
 */
public class ReverseKGroup1 {

    public static void main(String[] args) {
        ListNode head = BuildListNode.tailInsert(1, 2, 3, 4, 5);
        ListNode listNode = new ReverseKGroup1().reverseKGroup(head, 2);
        System.out.println(listNode);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode tail = head;
        for (int i = 0; i < k; i++) {
            tail = tail.next;
            if (tail == null) {
                return head;
            }
        }
        ListNode newHead = reverse(head, tail);
        head.next = reverseKGroup(tail, k);
        return newHead;
    }

    ListNode reverse(ListNode head, ListNode tail) {
        ListNode prev = null;
        while (head != tail) {
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
}
